package firewing.service.yahoo;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.logging.Logger;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import firewing.object.Dict.TrendSource;
import firewing.object.Trend;

public class YahooBuzzExtractor {
	private static final Logger log = Logger.getLogger(YahooBuzzExtractor.class
			.getName());

	private static final String TREND_LIST = "http://buzzlog.yahoo.com/overall/";

	public static ArrayList<Trend> run() {
		ArrayList<Trend> ret = parseListPage();

		return ret;
	}

	private static ArrayList<Trend> parseListPage() {
		ArrayList<Trend> ret = new ArrayList<Trend>();
		Trend t = null;

		try {
			// load the URL
			URL url = new URL(TREND_LIST);
			URLConnection conn = url.openConnection();
			conn.setAllowUserInteraction(false);
			conn.setReadTimeout(0);
			conn.setConnectTimeout(0);

			String s = "", content = "";
			BufferedReader in = new BufferedReader(new InputStreamReader(
					conn.getInputStream()));
			while ((s = in.readLine()) != null) {
				content += s;
			}

			// parse the page as DOM
			Document doc = Jsoup.parse(content);
			Element element = doc.getElementById("topsearchleaders");
			for (Element e : element.getElementsByTag("tr")) {
				for (Element tdElement : e.getElementsByTag("td")) {
					if (tdElement.hasClass("trank")) {
						if (t != null) {
							ret.add(t);
						}

						t = new Trend();
						t.setSource(TrendSource.YahooBuzz);
						t.setYahooBuzzLeader(true); // default leader entry
						t.setRank(Integer.parseInt(tdElement.text()));
					} else if (tdElement.hasClass("prev")) {
						if (tdElement.text().equals("-")) {
							t.setPrevRank(0);
						} else {
							t.setPrevRank(Integer.parseInt(tdElement.text()));
						}
					} else if (tdElement.hasClass("subject")) {
						String[] array = tdElement.text().split("\\(|\\)");
						t.setPhrase(array[0].trim());
						if (array.length == 2) {
							t.setDaysOnChart(Integer.parseInt(array[1].trim()));
						}
					} else if (tdElement.hasClass("red")
							|| tdElement.hasClass("green")) {
						t.setYahooBuzzMove(tdElement.text());
					} else if (tdElement.hasClass("score")) {
						t.setYahooBuzzScore(Integer.parseInt(tdElement.text()));
					} else if (tdElement.hasClass("mover")) {
						t.setYahooBuzzOneDayMove(tdElement.text());
						t.setYahooBuzzLeader(false); // a mover entry
					}
				}
			}
			ret.add(t);

			return ret;
		} catch (Exception e) {
			e.printStackTrace();

			log.severe("Failed to load URL.");

			return null;
		}
	}

	private static void parseDetailPage() {

	}

	public static void main(String[] args) {
		ArrayList<Trend> result = run();

		for (Trend t : result) {
			System.out.println(t.getRank() + ", " + t.getPhrase());
			if (t.isYahooBuzzLeader()) {
				System.out.println("Leader" + ", " + t.getYahooBuzzScore()
						+ ", " + t.getYahooBuzzMove() + ", " + t.getPrevRank()
						+ ", " + t.getDaysOnChart());
			} else {
				System.out.println("Mover" + ", " + t.getYahooBuzzOneDayMove());
			}
		}
	}
}
